package com.analysis.controller;

import com.analysis.model.AnalysisResponse;
import com.analysis.service.JarAnalysisService;
import com.analysis.service.ExportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/analysis")
@RequiredArgsConstructor
public class JarAnalysisController {

    private final JarAnalysisService jarAnalysisService;
    private final ExportService exportService;

    @PostMapping("/compare")
    public ResponseEntity<?> compareJars(
            @RequestParam("oldJar") MultipartFile oldJar,
            @RequestParam("newJar") MultipartFile newJar) {
        try {
            // 验证文件
            validateFile(oldJar, "旧版本");
            validateFile(newJar, "新版本");

            // 执行分析
            log.info("开始分析JAR文件: {} vs {}", oldJar.getOriginalFilename(), newJar.getOriginalFilename());
            AnalysisResponse response = jarAnalysisService.analyzeJars(oldJar, newJar);
            log.info("分析完成");

            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("请求参数错误: {}", e.getMessage());
            return createErrorResponse(HttpStatus.BAD_REQUEST, e.getMessage());
        } catch (IOException e) {
            log.error("文件处理错误", e);
            return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "文件处理失败，请重试");
        } catch (Exception e) {
            log.error("分析过程出错", e);
            return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "分析过程出错，请重试");
        }
    }

    @PostMapping("/export/{type}")
    public ResponseEntity<?> exportReport(
            @PathVariable String type,
            @RequestBody AnalysisResponse analysisResponse) {
        try {
            byte[] content;
            String filename;
            MediaType mediaType;

            switch (type.toLowerCase()) {
                case "excel":
                    content = exportService.exportToExcel(analysisResponse);
                    filename = "jar_analysis_report.xlsx";
                    mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    break;
                case "pdf":
                    content = exportService.exportToPdf(analysisResponse);
                    filename = "jar_analysis_report.pdf";
                    mediaType = MediaType.APPLICATION_PDF;
                    break;
                default:
                    return createErrorResponse(HttpStatus.BAD_REQUEST, "不支持的导出格式");
            }

            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                    .body(content);
        } catch (Exception e) {
            log.error("导出报告失败", e);
            return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "导出失败，请重试");
        }
    }

    private void validateFile(MultipartFile file, String fileType) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException(fileType + "JAR文件不能为空");
        }
        if (!file.getOriginalFilename().toLowerCase().endsWith(".jar")) {
            throw new IllegalArgumentException(fileType + "文件必须是JAR格式");
        }
        if (file.getSize() > 100 * 1024 * 1024) { // 100MB
            throw new IllegalArgumentException(fileType + "文件大小不能超过100MB");
        }
    }

    private ResponseEntity<Map<String, String>> createErrorResponse(HttpStatus status, String message) {
        Map<String, String> response = new HashMap<>();
        response.put("message", message);
        return ResponseEntity.status(status).body(response);
    }
}
